/**
 * @author Leong Wai Lun A0032831R
 */

package properties;

import java.lang.reflect.Field;
import java.util.Properties;

public abstract class PropertiesDTO {
	protected String id;

	public PropertiesDTO(String id) {
		super();
		this.id = id;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}
	
	public Properties getProperties() {
		Properties currentProperties = new Properties();
		
		currentProperties.put("id", id);
		Field[] fields = this.getClass().getDeclaredFields();
		for (Field currentField : fields) {
			currentField.setAccessible(true);
			try {
				currentProperties.put(currentField.getName(), currentField.get(this).toString());
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
                            
                        } catch (NullPointerException e) {
                            currentProperties.put(currentField.getName(), "");
                        }
                        
		}
		
		return currentProperties;
	}

	public void setProperties(Properties currentProperties) {
		id = currentProperties.getProperty("id");
		System.out.println("id: " + id +" class: " + this.getClass().toString() );
		Field[] fields = this.getClass().getDeclaredFields();
		
		for (Field currentField : fields) {
			currentField.setAccessible(true);
			try {
				Class<?> type = currentField.getType();
				String fieldString = currentProperties.get(currentField.getName()).toString();
				if (type == boolean.class)
					currentField.setBoolean(this, fieldString.equals("true") ? true : false);
				else if (type == int.class)
					currentField.setInt(this, Integer.parseInt(fieldString));
				else
					currentField.set(this, fieldString);
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (NullPointerException e) {
				currentProperties.put(currentField.getName(), "");
			}
		}
	}
}
